#include "simple_encrypt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <android/log.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "ssl/md5.h"
#include <dirent.h>
#define  ENCRYPT_PATH  "/mnt/sdcard/.doctoran/"
#define  ENCRYPT_SUCESS  1
#define  ENCRYPT_FAILED  0
#define LOG_TAG  "jni_encrypt"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

int createDir();  // declare create direcory function
int startEncrypt(unsigned char * file_path, unsigned char * file_name) {
	LOGI("startEncrypt:%s", file_path);
	FILE *fp;
	int flen;
	const char *error = "file open error";
	char *p;
	if ((fp = fopen(file_path, "r+")) == NULL) {
		return ENCRYPT_FAILED;
	}
	fseek(fp, 0L, SEEK_END);
	flen = ftell(fp); //获取文件大小
	LOGI("file length is :%d", flen);
	p = (char *) malloc(flen + 1);
	if (p == NULL) {
		fclose(fp);
		return ENCRYPT_FAILED;
	}
	fseek(fp, 0L, SEEK_SET);
	fread(p, flen, 1, fp);
	p[flen] = 0;
	fclose(fp);
	LOGI("read result ,%s", p);

	if (createDir() == 0) {
		return ENCRYPT_FAILED;
	}
	char dir[2048] = ENCRYPT_PATH;
	unsigned char md[16];
	MD5_CTX md5; //declare md5 struct
	MD5Init(&md5); //init
	MD5Update(&md5, file_name, strlen(file_name));
	MD5Final(&md5, md);
	char buf[33] = { '\0' };
	char tmp[3] = { '\0' }; // \0是结束符
	LOGI("加密前:%s", file_name);
	int i = 0;
	for (i = 0; i < 16; i++) {
		sprintf(tmp, "%02X", md[i]); //将字符数组格式化为十六进制(MD5以十六进制表示)
		strcat(buf, tmp);
	}LOGI("字符指针的内容为:%s", buf);
	strcat(dir, buf);

	LOGI("long_name,%s", dir);
	FILE *wfp;

	char ch, *str;

	if ((wfp = fopen(dir, "w+")) != NULL) {
		fputs(p, wfp);
		fclose(wfp);
		return ENCRYPT_SUCESS;
	} else {
		return ENCRYPT_FAILED;
	}
}

int createDir() {
	LOGI("called create dir");
	char * directory = ENCRYPT_PATH;
	FILE *fexist;
	DIR *d;
	if (!(d = opendir(directory))) {
		int status = mkdir(directory, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
		if (status == 0) {
			LOGI("create directory .an sucess");
			return 1;
		} else if (status == -1) {
			LOGI("create directory .an failed");
			return 0;
		}
	} else {
		LOGI("directory .an has created ");
		return 1;
	}

}
char * startDecrypt(unsigned char * file_path) {

}
